/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.io.InputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * <p>Project: javaweb - DbUtil
 * <p>Powered by webrx On 2022-03-07 18:00:15
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class DbUtil {
    private Connection conn;
    private QueryRunner run;

    public DbUtil() {
        try {
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties");
            Properties prop = new Properties();
            prop.load(is);
            DruidDataSource ds = new DruidDataSource();
            ds.setConnectProperties(prop);
            System.out.println(ds.getDriverClassName());
            this.conn = ds.getConnection();
            this.run = new QueryRunner(ds);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<String> dbs(){
        List<String> list = new ArrayList<>();
        try {
            list = this.run.query("show databases",new ColumnListHandler<>());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public List<Map<String, Object>> query(String sql, MapListHandler mlh, Object... params) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            list = this.run.query(sql, mlh, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
